<template>
  <div class="wms-item-page art-full-height">
    <!-- 搜索栏 -->
    <WmsItemSearch
      v-model:filter="searchFilter"
      @search="handleSearch"
      @reset="handleReset"
    />

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格工具栏 -->
      <ArtTableHeader
        v-model:columns="columnChecks"
        @refresh="refreshData"
        layout="refresh,size,fullscreen,columns,settings"
      >
        <template #left>
          <ElButton type="primary" @click="showDialog('add')" v-ripple>
            <ElIcon><Plus /></ElIcon>
            新增商品
          </ElButton>
          <ElButton @click="handleExport" v-ripple>
            <ElIcon><Download /></ElIcon>
            导出
          </ElButton>
          <ElButton @click="showCategoryDialog" v-ripple>
            <ElIcon><FolderOpened /></ElIcon>
            分类管理
          </ElButton>
          <ElButton @click="showBrandDialog" v-ripple>
            <ElIcon><Star /></ElIcon>
            品牌管理
          </ElButton>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="isLoading"
        :data="tableData"
        :columns="columns"
        :pagination="paginationState"
        @selection-change="handleSelectionChange"
        @pagination:size-change="onPageSizeChange"
        @pagination:current-change="onCurrentPageChange"
      >
        <!-- 自定义列插槽 -->
        <template #itemInfo="{ row }">
          <div class="item-info">
            <div class="item-name">{{ row.itemName }}</div>
            <div class="item-code">{{ row.itemCode }}</div>
          </div>
        </template>

        <template #categoryInfo="{ row }">
          <ElTag v-if="row.categoryName" type="info">{{
            row.categoryName
          }}</ElTag>
          <span v-else class="text-placeholder">-</span>
        </template>

        <template #brandInfo="{ row }">
          <ElTag v-if="row.brandName" type="warning">{{ row.brandName }}</ElTag>
          <span v-else class="text-placeholder">-</span>
        </template>

        <template #skuCount="{ row }">
          <ElBadge :value="row.skuCount || 0" type="primary">
            <ElButton size="small" text @click="showSkuDialog(row)">
              查看SKU
            </ElButton>
          </ElBadge>
        </template>

        <template #actions="{ row }">
          <ElButton type="primary" link @click="handleEdit(row)">
            <ElIcon><Edit /></ElIcon>
            编辑
          </ElButton>
          <ElButton type="info" link @click="showSkuDialog(row)">
            <ElIcon><List /></ElIcon>
            SKU
          </ElButton>
          <ElButton type="danger" link @click="handleDelete(row)">
            <ElIcon><Delete /></ElIcon>
            删除
          </ElButton>
        </template>
      </ArtTable>
    </ElCard>

    <!-- 商品弹窗 -->
    <WmsItemDialog
      v-model:visible="dialogVisible"
      :type="dialogType"
      :item-data="currentItemData"
      @submit="handleDialogSubmit"
    />

    <!-- SKU管理弹窗 -->
    <WmsSkuDialog
      v-model:visible="skuDialogVisible"
      :item-data="currentItemData"
      @submit="handleSkuDialogSubmit"
    />

    <!-- 分类管理弹窗 -->
    <WmsItemCategoryDialog
      v-model:visible="categoryDialogVisible"
      @submit="handleCategoryDialogSubmit"
    />

    <!-- 品牌管理弹窗 -->
    <WmsItemBrandDialog
      v-model:visible="brandDialogVisible"
      @submit="handleBrandDialogSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useTable } from "@/composables/useTable";
import { listItem, delItem, exportItem } from "@/api/wms/item";
import { useWmsStore } from "@/store/modules/wms";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Download,
  Edit,
  Delete,
  List,
  FolderOpened,
  Star,
} from "@element-plus/icons-vue";

// 导入子组件
import WmsItemSearch from "./components/WmsItemSearch.vue";
import WmsItemDialog from "./components/WmsItemDialog.vue";
import WmsSkuDialog from "./components/WmsSkuDialog.vue";
import WmsItemCategoryDialog from "./components/WmsItemCategoryDialog.vue";
import WmsItemBrandDialog from "./components/WmsItemBrandDialog.vue";

defineOptions({ name: "WmsItem" });

const wmsStore = useWmsStore();

// 表格配置
const {
  tableData,
  columns,
  columnChecks,
  isLoading,
  paginationState,
  searchFilter,
  onPageSizeChange,
  onCurrentPageChange,
  refreshData,
  handleSearch,
  handleReset,
} = useTable<WMS.Item.ItemInfo>({
  core: {
    apiFn: listItem,
    apiParams: {
      current: 1,
      size: 20,
    },
    columnsFactory: () => [
      {
        type: "selection",
        width: 50,
      },
      {
        prop: "itemInfo",
        label: "商品信息",
        slot: "itemInfo",
        minWidth: 200,
        fixed: "left",
      },
      {
        prop: "categoryInfo",
        label: "商品分类",
        slot: "categoryInfo",
        width: 120,
      },
      {
        prop: "brandInfo",
        label: "商品品牌",
        slot: "brandInfo",
        width: 120,
      },
      {
        prop: "unit",
        label: "计量单位",
        width: 100,
        align: "center",
      },
      {
        prop: "skuCount",
        label: "SKU数量",
        slot: "skuCount",
        width: 120,
        align: "center",
      },
      {
        prop: "remark",
        label: "备注",
        minWidth: 150,
        showOverflowTooltip: true,
      },
      {
        prop: "createTime",
        label: "创建时间",
        width: 180,
        formatter: (row) => row.createTime || "-",
      },
      {
        prop: "actions",
        label: "操作",
        width: 200,
        slot: "actions",
        fixed: "right",
      },
    ],
  },
});

// 弹窗状态
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const currentItemData = ref<WMS.Item.ItemInfo | null>(null);

const skuDialogVisible = ref(false);
const categoryDialogVisible = ref(false);
const brandDialogVisible = ref(false);

// 选中的行
const selectedRows = ref<WMS.Item.ItemInfo[]>([]);

// 处理选择变化
const handleSelectionChange = (selection: WMS.Item.ItemInfo[]) => {
  selectedRows.value = selection;
};

// 显示商品弹窗
const showDialog = (type: "add" | "edit", itemData?: WMS.Item.ItemInfo) => {
  dialogType.value = type;
  currentItemData.value = itemData || null;
  dialogVisible.value = true;
};

// 编辑商品
const handleEdit = (row: WMS.Item.ItemInfo) => {
  showDialog("edit", row);
};

// 删除商品
const handleDelete = async (row: WMS.Item.ItemInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品"${row.itemName}"吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    await delItem(row.id);
    ElMessage.success("删除成功");
    refreshData();
  } catch (_error) {
    if (_error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 显示SKU管理弹窗
const showSkuDialog = (row: WMS.Item.ItemInfo) => {
  currentItemData.value = row;
  skuDialogVisible.value = true;
};

// 显示分类管理弹窗
const showCategoryDialog = () => {
  categoryDialogVisible.value = true;
};

// 显示品牌管理弹窗
const showBrandDialog = () => {
  brandDialogVisible.value = true;
};

// 处理商品弹窗提交
const handleDialogSubmit = () => {
  dialogVisible.value = false;
  refreshData();
};

// 处理SKU弹窗提交
const handleSkuDialogSubmit = () => {
  skuDialogVisible.value = false;
  refreshData();
};

// 处理分类弹窗提交
const handleCategoryDialogSubmit = () => {
  categoryDialogVisible.value = false;
  // 刷新分类数据
  wmsStore.refreshBasicData("category");
};

// 处理品牌弹窗提交
const handleBrandDialogSubmit = () => {
  brandDialogVisible.value = false;
  // 刷新品牌数据
  wmsStore.refreshBasicData("brand");
};

// 导出数据
const handleExport = async () => {
  try {
    const response = await exportItem(searchFilter.value);
    // 处理文件下载
    const url = window.URL.createObjectURL(response);
    const link = document.createElement("a");
    link.href = url;
    link.download = `商品数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success("导出成功");
  } catch (error) {
    ElMessage.error("导出失败");
  }
};

// 初始化数据
onMounted(() => {
  // 初始化基础数据
  wmsStore.initAllBasicData();
});
</script>

<style lang="scss" scoped>
.wms-item-page {
  .item-info {
    .item-name {
      font-weight: 500;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }

    .item-code {
      font-size: 12px;
      color: var(--el-text-color-regular);
    }
  }

  .text-placeholder {
    color: var(--el-text-color-placeholder);
  }
}
</style>
